function AllReady() {
  var mstform = Ext.getCmp("PoUrgeM"); //获取容器
  var PhidPc = mstform.queryById("PhidPc");
  var PhidCnt = mstform.queryById("PhidContract");
  var dgrid = Ext.getCmp("PoUrgeD");
  var Toolbar = Ext.getCmp("toolbar");
  var dstore = dgrid.store;
  var user_pro_type = mstform.queryById("user_pro_type");
  var user_ywlx = mstform.queryById("user_ywlx");
  var PhidBuyer = mstform.queryById("PhidBuyer");
  var user_regional_center = mstform.queryById("user_regional_center");
  var user_ejbm = mstform.queryById("user_ejbm");
  var user_division = mstform.queryById("user_division"); //获取字段
  var user_product_line = mstform.queryById("user_product_line");
  var TotalMony = mstform.queryById("TotalMony");
  var TotalTaxMony = mstform.queryById("TotalTaxMony");
  var user_tax_amt = mstform.queryById("user_tax_amt");
  var PhidBuyer = mstform.queryById("PhidBuyer");
  var BuyerPhone = mstform.queryById("BuyerPhone");
  var PhidOrderDept = mstform.queryById("PhidOrderDept");
  var user_gys = mstform.queryById("user_gys");
  var user_cnt_no = mstform.queryById("user_cnt_no");
  var ContractName = mstform.queryById("ContractName");
  var PhidVendor = mstform.queryById("PhidVendor");

  user_cnt_no.on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
    var pc = mstform.getItem("PhidPc").getValue();
    if (Ext.isEmpty(pc)) {
      Ext.Msg.alert("提示", "请先选择项目！");
      mstform.getItem("PhidPc").focus();
      return false;
    } else {
      mstform.getItem("user_cnt_no").setOutFilter({
        phid_pc: pc, //phid_pc 字段是通用帮助中的字段
      });
    }
  });
  user_cnt_no.addListener("helpselected", function (data) {
    //表头帮助窗口选择后触发
    console.log(data);
    PhidCnt.setValue(data.data.phid);
    ContractName.setValue(data.data.bill_name);
    PhidVendor.setValue(data.data.phid_supply_ent);
    BatchBindCombox([PhidVendor]);
    BatchBindCombox([PhidCnt]);
  });
  PhidCnt.addListener("change", function () {
    getCntPayDetailInfo();
    // console.log("PhidCnt change event fired");
    execServer("getCntInfo", { cnt: PhidCnt.getValue() }, function (res) {
      const datasGetCntInfo = JSON.parse(res.data)[0].extendObjects;

      if (datasGetCntInfo) {
        if (datasGetCntInfo.pc) {
          console.log(datasGetCntInfo.pc, "PhidPc.setValue(datasGetCntInfo?.pc");

          PhidPc.setValue(datasGetCntInfo?.pc);
          BatchBindCombox([PhidPc]);
        }
        if (datasGetCntInfo.upt) {
          user_pro_type.setValue(datasGetCntInfo.upt);
        }
        if (datasGetCntInfo.ubt) {
          user_ywlx.setValue(datasGetCntInfo.ubt);
          BatchBindCombox([user_ywlx]);
        }
        if (datasGetCntInfo.up) {
          PhidBuyer.setValue(datasGetCntInfo.up);
          BatchBindCombox([PhidBuyer]);
        }
      }
    });
  });
  PhidBuyer.addListener("change", function (args) {
    // console.log(args.value, "采购员");
    execServer("getModileYHD", { phidPhonea: args.value }, function (res) {
      try {
        var obj = JSON.parse(res.data);
        BuyerPhone.setValue(obj[0].extendObjects.mobile1);
      } catch (error) {}
    });
  });
  PhidPc.addListener("change", function (args) {
    if (PhidPc.getValue()) {
      getSyQty(mstform.queryById("PhidPc").getValue());

      //----------
      execServer("getPtInfoByPhid", { phid: PhidPc.getValue() }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        //帮助字段赋值
        // console.log(datas, "datas");
        user_division.setValue(datas.division_phid);
        user_product_line.setValue(datas.midwife_phid);
        user_regional_center.setValue(datas.regional_center_phid);
        user_ejbm.setValue(datas.org_phid);
        BatchBindCombox([user_ejbm]);
        BatchBindCombox([user_division]);
        BatchBindCombox([user_product_line]);
        BatchBindCombox([user_regional_center]);
      });

      // console.log(PhidCnt.getValue(), "PhidPc");
      if (!PhidCnt.getValue()) return;
      execServer("getCntMInfoByPhid", { phid: PhidCnt.getValue() }, function (res) {
        try {
          const datasGetCntMInfoByPhid = JSON.parse(res.data)[0].extendObjects;
          //帮助字段赋值
          // console.log(datasGetCntMInfoByPhid.dept_phid, "getCntMInfoByPhid");
          PhidOrderDept.setValue(datasGetCntMInfoByPhid.dept_phid);
          BatchBindCombox([PhidOrderDept]);
          user_gys.setValue(datasGetCntMInfoByPhid.supply_id);
          BatchBindCombox([user_gys]);
        } catch (error) {}
      });
    }
  });

  TotalMony.addListener("change", function () {
    user_tax_amt.setValue(TotalTaxMony.getValue() - TotalMony.getValue());
  });
  TotalTaxMony.addListener("change", function () {
    user_tax_amt.setValue(TotalTaxMony.getValue() - TotalMony.getValue());
  });

  // 用于状态是否发生变化
  let current = otype;
  dstore.on("datachanged", async function (dstore, eOpts) {
    const records = dstore.getRange();
    // for (const record of records) {
    //     //添加剩余量字段
    //     console.log(record,'每行数据');
    //     let num1 =  record.get("user_yhsyl")
    //     let num2 =  record.get("user_shsjljsl")
    //     console.log(num1,num2);

    //     if (num1>num2) {
    //         record.set("user_yhsyl",num2)
    //     }else{
    //         record.set("user_yhsyl",num1)
    //     }

    //     }

    mstform.on("dataready", async () => {
      console.log(`PhId`, mstform.queryById("PhId").getValue());
      if (current != otype) {
        current = otype;
        await getSyQty(mstform.queryById("PhidPc").getValue());
      }
      setDgridValue(dstore);
    });
    console.log(otype);

    if (otype == "add") {
      const records = dstore.getRange();
      console.log(dgrid.getStore().getRange()[0].data);
      if (!dgrid.getStore().getRange()[0].data.user_shsjljsl) {
        for (const record of records) {
          //添加剩余量字段
          // console.log(record);
          record.set("user_shsjljsl", window.qtytotal[record.get("PhidItemData")]);

          // record.set("Qty",window.qtytotal[record.get("PhidItemData")]);
          record.set("ConfirmQty", record.get("Qty"));
        }
      }
      changeQty();
    }
    if (otype != "add") return;
    setDgridValue(dstore);
  });

  function setDgridValue(dstore) {
    if (otype == "add" || otype == "edit") {
      const records = dstore.getRange();
      for (const record of records) {
        //添加剩余量字段
        // console.log(record);
        record.set("user_shsjljsl", window.qtytotal[record.get("PhidItemData")]);
        // if(!record.get("Qty")){
        //     record.set("Qty",window.qtytotal[record.get("PhidItemData")]);
        //   record.set("ConfirmQty",record.get("Qty"));

        // }
        try {
          // console.log(record.data.PhidItemData, "物料id");
          // console.log(record.data.PhidItemid, "物料id");
          execServer(
            "GETitemzq",
            {
              phid: record.data.PhidItemData,
            },
            function (res) {
              // console.log(res, "res");
              try {
                const obj = JSON.parse(res.data)[0].extendObjects;
                if (!obj.pur_lead) return; //如果为空则不执行
                record.set("user_ckarrival_dt", addDaysToDate(new Date(), obj.pur_lead));
                if (otype != "add") record.commit();
              } catch (error) {}
            }
          );
        } catch (error) {}
      }
      dgrid.getView().refresh();
    }
  }

  function changeQty(params) {
    dstore.each(function (item) {
      // 转换为数字
      let amt_1 = Ext.Number.from(item.get("user_yhsyl"), 0);
      let amt_2 = Ext.Number.from(item.get("user_shsjljsl"), 0);
      if (amt_1 > amt_2) {
        item.set("Qty", amt_2);
      } else {
        item.set("Qty", amt_1);
      }
      dgrid.getView().refresh();
    });
  }
  //监听表体编辑
  dgrid.addListener("edit", (dt, e) => {
    const dstore = e.record;
    // changeQty()
    console.log("监听读取", dstore);
    edit(dstore);
  });

  dgrid.getStore().addListener("datachanged", () => {
    if (otype == "view") return;
    mstform.queryById("user_yfkje").setValue((window._catch_cnt_pay?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
    mstform.queryById("user_yfksyje").setValue((window._catch_cnt_pay?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
  });

  //编辑逻辑
  function edit(dstore) {
    if (!dstore.get("PhidItemid")) return;
    const phidItem = dstore.get("PhidItemData");
    const Qty = dstore.get("Qty");
    const user_yhsyl = dstore.get("user_yhsyl");
    const user_shsjljsl = dstore.get("user_shsjljsl");
    const phid_pc = mstform.queryById("PhidPc").getValue();
    const user_yqarrival_dt = dstore.get("user_yqarrival_dt"); // 要求到货日期
    const user_ckarrival_dt = dstore.get("user_ckarrival_dt"); // 参考到货日期
    console.log(new Date(user_yqarrival_dt) < new Date(user_ckarrival_dt), "到货时间判断");
    if (user_yqarrival_dt && user_ckarrival_dt && new Date(user_yqarrival_dt) < new Date(user_ckarrival_dt)) {
      dstore.set("user_yqarrival_dt", undefined);
      Ext.Msg.alert("提示", "要求到货日期不能早于参考到货日期！");
    }
    console.log(`缓冲`, window.qtytotal, phidItem, phid_pc);
    if (Qty > user_yhsyl || Qty > user_shsjljsl) {
      Ext.Msg.alert("提示", "要货数量超出合同采购剩余量或深化设计剩余量");
      dstore.set("Qty", 0);
    }
    if ((Number(window.qtytotal[phidItem]) || 0) < Qty) {
      Ext.Msg.alert("提示", "要货数量超出！当前剩余：" + dstore.get("user_shsjljsl"));
      dstore.set("Qty", 0);
      dstore.set("ConfirmQty", 0);
    }
    // mstform.queryById("user_yfkhebl").setValue((_data[0].extendObjects.bal_percent || 0))
    mstform.queryById("user_yfkje").setValue((window._catch_cnt_pay?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
    mstform.queryById("user_yfksyje").setValue((window._catch_cnt_pay?.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
    // 判断数量是否超出(无缓冲去查找)
    dgrid.getView().refresh();
  }
  //查找当前物料可用数量
  getSyQty(mstform.queryById("PhidPc").getValue());
  async function getSyQty(phid_pc) {
    console.log(phid_pc, "项目状态");
    if (!phid_pc) return;
    //查找可用数量
    await execServer("getYhdQtyByPhidPcAndItem", { phid_pc }, async (res) => {
      console.log(`累计数量`, res);
      if (res.count == 0) {
        window.qtytotal = {};
        return;
      } else {
        let total = JSON.parse(res.data).reduce((value, item) => {
          value[item.extendObjects.phiditem] = item.extendObjects.qty;
          return value;
        }, {});
        console.log(`mstform.getItem("PhId").getValue()`, mstform.getItem("PhId").getValue());
        const phid = mstform.getItem("PhId").getValue() ? mstform.getItem("PhId").getValue() : "10086";
        //查询累计用过数量
        await execServer("getYhdPhidItemTotalQty", { phid_pc, phid }, (res) => {
          console.log(`累计用过数量`, res);
          let ysy = {};
          if (res.count == 0) {
          } else {
            const _data = JSON.parse(res.data);
            ysy = _data.reduce((value, item) => {
              value[item.extendObjects.phiditem] = item.extendObjects.qty;
              return value;
            }, {});
          }
          // 处理结果，搞出来剩余量
          window.qtytotal = {};
          for (let key in total) {
            console.log(key, total[key], ysy[key]);
            window.qtytotal[key] = (Number(total[key]) || 0) - (Number(ysy[key]) || 0);
          }
          console.log(`qtytotal`, window.qtytotal);
        });
      }
    });
  }

  // 获取合同条款
  otype == "view" && getCntPayDetailInfo();
  function getCntPayDetailInfo() {
    const cnt = mstform.queryById("PhidContract").getValue();
    if (!cnt) return;
    execServer("getCntPayDetailInfo", { cnt }, (res) => {
      // console.log(`获取合同明细`, res);
      if (res.count == 0) return;
      const _data = JSON.parse(res.data).filter((item) => {
        if ((Number(item.extendObjects.namephid) || 0) == 8570000000000001) {
          return item;
        }
      });

      // console.log(`_data`, _data, _data.length != 0);
      if (_data.length != 0) {
        window._catch_cnt_pay = _data[0].extendObjects;
        // console.log(`catch_cnt_pay`, window._catch_cnt_pay);
        mstform.queryById("user_yfkhebl").setValue(_data[0].extendObjects.bal_percent || 0);
        mstform.queryById("user_yfkje").setValue((_data[0].extendObjects.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
        mstform.queryById("user_yfksyje").setValue((_data[0].extendObjects.bal_percent || 0) * (Number(mstform.queryById("TotalTaxMony").getValue()) || 0));
      }
    });
  }
} //End -- AllReady

function addDaysToDate(date, days) {
  // 将传入的日期字符串转换为Date对象，如果本身就是Date对象则直接使用
  let targetDate = date instanceof Date ? date : new Date(date);
  // 获取时间戳，单位是毫秒，然后加上天数对应的毫秒数
  targetDate.setTime(targetDate.getTime() + days * 24 * 60 * 60 * 1000);
  return targetDate;
}

// function beforeSaveEdit() {
//     var mstform = Ext.getCmp("PoUrgeM"); //获取容器
//     var PhidPc = mstform.queryById("PhidPc");
//     execServer("getRkYhInfo", { pc: PhidPc }, function (res) {
// console.log(res);
//         const data = JSON.parse(res.data);
//         const ce = data[0].extendObjects.ce;
//         if (ce) {
//             Ext.Msg.alert('提示', "111")
//             return false;
//         } else {

//         }
//     });
// }
